package com.stylefeng.guns.modular.customer.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.support.VlidationUtil;
import com.stylefeng.guns.modular.customer.dao.PayPlanDao;
import com.stylefeng.guns.modular.customer.service.IPayPlanService;
import com.stylefeng.guns.modular.customer.transfer.PayPlanXlsM;
import com.stylefeng.guns.modular.customer.util.CustomerUtil;
import com.stylefeng.guns.modular.customer.warpper.PayPlanWrapper;
import com.stylefeng.guns.modular.customer.warpper.SaleWrapper;
import com.stylefeng.guns.modular.system.model.PayPlan;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.flowable.bpmn.model.DataGrid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 付款计划控制器
 *
 * @author fengshuonan
 * @Date 2018-04-03 15:01:52
 */
@Controller
@RequestMapping("/payPlan")
public class PayPlanController extends BaseController {

    private String PREFIX = "/customer/payPlan/";

    @Autowired
    private IPayPlanService payPlanService;

    @Autowired
    private PayPlanDao payPlanDao;

    /**
     * 跳转到付款计划首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "payPlan.html";
    }

    /**
     * 跳转到添加付款计划
     */
    @RequestMapping("/payPlan_add")
    public String payPlanAdd() {
        return PREFIX + "payPlan_add.html";
    }

    /**
     * 跳转到修改付款计划
     */
    @RequestMapping("/payPlan_update/{payPlanId}")
    public String payPlanUpdate(@PathVariable Integer payPlanId, Model model) {
        PayPlan payPlan = payPlanService.selectById(payPlanId);
        Map<String, Object> map = BeanKit.beanToMap(payPlan);
        model.addAttribute("item", new PayPlanWrapper(map).warp());
        LogObjectHolder.me().set(payPlan);
        return PREFIX + "payPlan_edit.html";
    }

    /**
     * 获取付款计划列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(
            @RequestParam(value = "customerCompanyId", required = false) Integer customerCompanyId,
            @RequestParam(value = "providerName", required = false) String providerName) {
        Page<PayPlan> page = new PageFactory<PayPlan>().defaultPage();
        List<Map<String, Object>> result = payPlanService.selectPayPlanesPage(page, customerCompanyId, providerName);
        page.setRecords((List<PayPlan>) new SaleWrapper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 新增付款计划
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @Permission
    @ApiOperation(value = "新增付款计划", tags = "付款计划", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "month", value = "月份 例如2017-04", dataType = "String", required = true),
                    @ApiImplicitParam(name = "providerName", value = "供应商名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "customerCompanyId", value = "客户id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "payAmount", value = "付款金额", dataType = "Float", required = true),
                    @ApiImplicitParam(name = "crash", value = "现金", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "silverTicket", value = "银票", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "silverTicketPeriod", value = "银票期限", dataType = "Integer", required = false),
                    @ApiImplicitParam(name = "businessTicket", value = "商票", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "businessTicketPeriod", value = "商票期限", dataType = "Integer", required = false),
                    @ApiImplicitParam(name = "hangxin", value = "航信", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "hangxinPeriod", value = "航信期限", dataType = "Integer", required = false),
            }
    )
    public Object add(@Validated PayPlan payPlan) throws NoPermissionException {
        if (!CustomerUtil.validEditPermission(payPlan.getCustomerCompanyId())) {
            throw new NoPermissionException();
        }
        payPlanService.insert(payPlan);
        return SUCCESS_TIP;
    }

    /**
     * 删除付款计划
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Permission(Const.ADMIN_NAME)
    public Object delete(@RequestParam Integer payPlanId) {
        payPlanService.deleteById(payPlanId);
        return SUCCESS_TIP;
    }

    /**
     * 修改付款计划
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    @ApiOperation(value = "更新付款计划", tags = "付款计划", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "id", value = "id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "month", value = "月份 例如2017-04", dataType = "String", required = true),
                    @ApiImplicitParam(name = "providerName", value = "供应商名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "customerCompanyId", value = "客户id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "payAmount", value = "付款金额", dataType = "Float", required = true),
                    @ApiImplicitParam(name = "crash", value = "现金", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "silverTicket", value = "银票", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "silverTicketPeriod", value = "银票期限", dataType = "Integer", required = false),
                    @ApiImplicitParam(name = "businessTicket", value = "商票", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "businessTicketPeriod", value = "商票期限", dataType = "Integer", required = false),
                    @ApiImplicitParam(name = "hangxin", value = "航信", dataType = "Float", required = false),
                    @ApiImplicitParam(name = "hangxinPeriod", value = "航信期限", dataType = "Integer", required = false),
            }
    )
    public Object update(@Validated PayPlan payPlan) throws NoPermissionException {
        PayPlan dbPayPlan = this.payPlanService.selectById(payPlan.getId());
        if (dbPayPlan == null) {
            throw new GunsException(BizExceptionEnum.DB_RESOURCE_NULL);
        }
        CustomerUtil.validEditPermission(dbPayPlan.getCustomerCompanyId());
        payPlanService.updateById(payPlan);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/payPlan_detail/{customerCompanyId}")
    public Object toDetail(@PathVariable("customerCompanyId") Integer customerCompanyId, Model model) {
        List<Map<String, Object>> list = payPlanDao.selectByCompanyId(customerCompanyId);
        model.addAttribute("items", new PayPlanWrapper(list).warp());
        return PREFIX + "payPlan_detail.html";
    }

    /**
     * 付款计划详情
     */
    @RequestMapping(value = "/detail/{payPlanId}")
    @ResponseBody
    public Object detail(@PathVariable("payPlanId") Integer payPlanId) {
        PayPlan payPlan = payPlanService.selectById(payPlanId);
        if (payPlan == null) {
            throw new GunsException(BizExceptionEnum.DB_RESOURCE_NULL);
        }
        Map<String, Object> map = BeanKit.beanToMap(payPlan);
        CustomerUtil.putAuthority(map,payPlan.getCustomerCompanyId());
        return new PayPlanWrapper(map).warp();
    }

    /**
     * 导出Excel模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "付款计划模板");
        modelMap.put(NormalExcelConstants.CLASS, PayPlanXlsM.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("付款计划列表",
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, PayPlanXlsM.example());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }


    @RequestMapping(method = RequestMethod.POST, path = "/importExcel")
    @ResponseBody
    public Object importExcel(MultipartHttpServletRequest multipartHttpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : multipartFileMap.entrySet()) {
            MultipartFile file = entity.getValue();//获取文件上传对象
            ImportParams importParams = new ImportParams();
            //标题行数
            importParams.setTitleRows(1);
            //表头行数
            importParams.setHeadRows(1);
            //是否需要保存上传的EXCEL
            importParams.setNeedSave(false);
            List<PayPlanXlsM> result = ExcelImportUtil.importExcel(file.getInputStream(), PayPlanXlsM.class, importParams);
            VlidationUtil.validateList(result);
            payPlanService.insertXlsListPayPlan(result);
        }
        return "文件导入成功";
    }
}
